<?php

namespace mpend\modules\demand\models;

use Yii;
use yii\db\Exception;
use common\helpers\StringHelper;
use common\helpers\ArrayHelper;
use common\models\demand\DemandSolution;
use common\models\demand\DemandAttach;

/**
 * 需求解决方案回复模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DemandSolutionForm extends BaseDemandForm {

    /**
     * @var string 直播ID
     */
    public $demand_id;

    /**
     * @inheritdoc
     */
    public function rules() {
        return ArrayHelper::merge(parent::rules(), [
            [['demand_id'], 'required'],
            [['demand_id'], 'integer'],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'demand_id' => '需求内容',
        ]);
    }

    /**
     * 加密流验证操作
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->validateError('方案信息验证失败');
        }
        $model = new DemandSolution();
        $model->setAttributes([
            'user_id' => $this->user_id,
            'demand_id' => $this->demand_id,
            'content' => $this->content,
            'title' => StringHelper::truncate($this->content, 250),
            'status' => DemandSolution::STATUS_ACTIVE
        ]);
        $images = $this->images;
        $attachs = $this->getAttachFiles();
        //方案附件
        $attachModel = new DemandAttach();
        $attachModel->user_id = $this->user_id;
        $attachModel->demand_id = $this->demand_id;
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('需求创建失败！');
            }
            $attachModel->solution_id = $model->id;
            if (!empty($images)) {
                foreach ($images as $image) {
                    $_attach = clone $attachModel;
                    $_attach->format = DemandAttach::FORMAT_IMAGE;
                    $_attach->path = $image;
                    if (!$_attach->save()) {
                        throw new Exception('图片保存失败！');
                    }
                }
            }
            if (!empty($attachs)) {
                foreach ($attachs as $attach) {
                    $_attach = clone $attachModel;
                    $_attach->setAttributes($attach);
                    if (!$_attach->save()) {
                        throw new Exception('附件保存失败！');
                    }
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return [
            'description' => '回复成功',
            'image' => '/static/images/blank/success.png',
        ];
    }

}
